import { template } from '@szzj/utils';
import Mime from 'mime/Mime';

// @ts-ignore
import standardTypes from 'mime/types/standard.js';
// @ts-ignore
import otherTypes from 'mime/types/other.js';
var mime = new Mime(standardTypes, otherTypes);
var Alias = {
  image: '.png,.apng,.avif,.gif,.jpeg,.svg,.webp,.bmp,.ico,.jfif,.pjpeg,.pjp',
  audio: '.mp3,.wav,.wma,.ogg,.aac,.flac,.m4a',
  vedio: '.mp4,.avi,.rmvb,.rm,.wmv,.mkv,.flv,.mov',
  word: '.doc,.docx',
  excel: '.xls,.xlsx',
  pdf: '.pdf',
  ppt: '.ppt,.pptx',
};

/**
 * accept 别名转换
 * @doc https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers
 * @doc https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types
 * @doc https://www.iana.org/assignments/media-types/media-types.xhtml
 */
export var convetAliasToExtension = function convetAliasToExtension(accept) {
  return accept
    .split(',')
    .map(function (type) {
      var _Alias;
      return (_Alias = Alias[type]) !== null && _Alias !== void 0 ? _Alias : type;
    })
    .join(',');
};

/** 校验文件类型 */
var validateFileType = function validateFileType(file, _ref) {
  var accept = _ref.accept,
    errorMessages = _ref.errorMessages;
  var accepted = accept.split(',').some(function (type) {
    var names = file.name.split('.');
    var extension = '.'.concat(names[names.length - 1]);

    // 文件扩展名匹配或 MIME 类型匹配
    return (
      extension === type ||
      file.type === type ||
      !!(mime.getType(type) && file.type === mime.getType(type))
    );
  });
  if (!accepted) {
    var msg = template(
      errorMessages === null || errorMessages === void 0 ? void 0 : errorMessages.typeError,
    )({
      accept: accept,
    });
    throw new Error(msg);
  }
};

/** 校验文件大小 */
var validateFileSize = function validateFileSize(file, _ref2) {
  var maxSize = _ref2.maxSize,
    errorMessages = _ref2.errorMessages;
  var lessThenMaxSize = file.size / 1024 / 1024 < maxSize;
  if (!lessThenMaxSize) {
    var msg = template(
      errorMessages === null || errorMessages === void 0 ? void 0 : errorMessages.overSize,
    )({
      maxSize: maxSize,
    });
    throw new Error(msg);
  }
};

/** 上传文件前验证 */
export var createFileValidator = function createFileValidator(_ref3) {
  var accept = _ref3.accept,
    maxSize = _ref3.maxSize,
    errorMessages = _ref3.errorMessages;
  return function (file) {
    if (accept) {
      validateFileType(file, {
        accept: accept,
        errorMessages: errorMessages,
      });
    }
    if (maxSize) {
      validateFileSize(file, {
        maxSize: maxSize,
        errorMessages: errorMessages,
      });
    }
  };
};
